package com.deliveryservicesystem.service.crud.impl;

import com.deliveryservicesystem.app.exceptions.NonexistentEntityException;
import com.deliveryservicesystem.app.exceptions.PreexistingEntityException;
import com.deliveryservicesystem.dataaccess.PersistenceDbManager;
import com.deliveryservicesystem.model.Delivery;
import com.deliveryservicesystem.model.Route;
import com.deliveryservicesystem.service.crud.RouteCrudService;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 * File Name: RouteCrudServiceImpl.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.service.crud.impl
 * Author: Lance
 * Date: Jun 20, 2012
 * Editor:
 */
public class RouteCrudServiceImpl implements RouteCrudService
{

    private static final long serialVersionUID = 1L;
    private EntityManagerFactory emf = null;

    /**
     * Create the new CRUD service. Internally setting the EntityManagerFactory
     * using database details from database properties
     */
    public RouteCrudServiceImpl()
    {
        PersistenceDbManager persistenceManager = PersistenceDbManager.getInstance();
        this.emf = persistenceManager.getEntityManagerFactory();
    }

    @Override
    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    @Override
    public void create(Route route) throws PreexistingEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Delivery deliveryNo = route.getDeliveryNo();
            if (deliveryNo != null)
            {
                deliveryNo = em.getReference(deliveryNo.getClass(), deliveryNo.getDeliveryNo());
                route.setDeliveryNo(deliveryNo);
            }
            em.persist(route);
            if (deliveryNo != null)
            {
                deliveryNo.getRouteList().add(route);
                deliveryNo = em.merge(deliveryNo);
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            if (findById(route.getRouteNo()) != null)
            {
                throw new PreexistingEntityException("Route " + route + " already exists.", ex);
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void edit(Route route) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Route persistentRoute = em.find(Route.class, route.getRouteNo());
            Delivery deliveryNoOld = persistentRoute.getDeliveryNo();
            Delivery deliveryNoNew = route.getDeliveryNo();
            if (deliveryNoNew != null)
            {
                deliveryNoNew = em.getReference(deliveryNoNew.getClass(), deliveryNoNew.getDeliveryNo());
                route.setDeliveryNo(deliveryNoNew);
            }
            route = em.merge(route);
            if (deliveryNoOld != null && !deliveryNoOld.equals(deliveryNoNew))
            {
                deliveryNoOld.getRouteList().remove(route);
                deliveryNoOld = em.merge(deliveryNoOld);
            }
            if (deliveryNoNew != null && !deliveryNoNew.equals(deliveryNoOld))
            {
                deliveryNoNew.getRouteList().add(route);
                deliveryNoNew = em.merge(deliveryNoNew);
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = route.getRouteNo();
                if (findById(id) == null)
                {
                    throw new NonexistentEntityException("The route with id " + id + " no longer exists.");
                }
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Route route;
            try
            {
                route = em.getReference(Route.class, id);
                route.getRouteNo();
            }
            catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The route with id " + id + " no longer exists.", enfe);
            }
            Delivery deliveryNo = route.getDeliveryNo();
            if (deliveryNo != null)
            {
                deliveryNo.getRouteList().remove(route);
                deliveryNo = em.merge(deliveryNo);
            }
            em.remove(route);
            em.getTransaction().commit();
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public List<Route> findEntities()
    {
        return findRouteEntities(true, -1, -1);
    }

    @Override
    public List<Route> findEntities(int maxResults, int firstResult)
    {
        return findRouteEntities(false, maxResults, firstResult);
    }

    private List<Route> findRouteEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Route.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public Route findById(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Route.class, id);
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public int count()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Route> rt = cq.from(Route.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        }
        finally
        {
            em.close();
        }
    }
}
